package com.gzmu.myprint.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzmu.myprint.mapper.RepairMapper;
import com.gzmu.myprint.model.*;
import com.gzmu.myprint.wx.msg.util.SMessage;
import com.gzmu.myprint.wx.util.ParamesAPI;
import com.gzmu.myprint.wx.util.WeixinUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.gzmu.myprint.constant.Constant.*;
import static com.gzmu.myprint.vo.CommonUtil.getOpenid;

@Controller
public class RepairController {
    @Autowired
    private RepairMapper repairMapper;

    @ResponseBody
    @RequestMapping(value = "/getRepairOpenid", produces = "text/html;charset=UTF-8")
    public String getRepairOpenid(String code){
        System.out.println("+++code: " + code);
        String content = null;
        Map map = new HashMap();
        ObjectMapper mapper = new ObjectMapper();

        Teacher teacher = new Teacher();
        String openid = getOpenid(code,BX_ID,BX_SECRET);
        if(!StringUtils.isBlank(openid)){
            openid = openid.replace("\"", "").trim();
            teacher = repairMapper.findUerByOpenId(openid);
            if (teacher == null){
                teacher = new Teacher();
                teacher.setOpenid(openid);
                repairMapper.insertTeacher(teacher);
                teacher.setId(0);
            }
        }
        try {
            map.put("teacher", teacher);
            content = mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/branchList", produces = "text/html;charset=UTF-8")
    public String branchList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> list = repairMapper.branchList();
        map.put("list",list);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/updateTeacher", produces = "text/html;charset=UTF-8")
    public String updateTeacher(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        Teacher teacher = new Teacher();
        ObjectMapper mapper = new ObjectMapper();
        String wxid = request.getParameter("wxid");
        String openid = request.getParameter("openid");
        String nickName = request.getParameter("nickName");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String avatarUrl = request.getParameter("avatarUrl");
        String phone = request.getParameter("phone");
        String branch = request.getParameter("branch");
        String title = request.getParameter("title");
        String role = request.getParameter("role");
        teacher.setWxid(wxid);
        teacher.setOpenid(openid);
        teacher.setNickName(nickName);
        teacher.setName(name);
        teacher.setGender(gender);
        teacher.setAvatarUrl(avatarUrl);
        teacher.setPhone(phone);
        teacher.setBranch(branch);
        teacher.setTitle(title);
        teacher.setRole(Integer.valueOf(role));
        System.out.println("+++openid:" + openid + " role:" + role);
        int res = repairMapper.updateTeacher(teacher);
        try {
            map.put("res",res);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }
//
//    @ResponseBody
//    @RequestMapping(value = "/buildList", produces = "text/html;charset=UTF-8")
//    public String buildList(HttpServletRequest request) {
//        List<String> builds = repairMapper.selectAllBuild();
//        Map<String, Object> map = new HashMap<String, Object>();
//        //System.out.println("+++keyword:" + keyword);
//        map.put("builds",builds);
//        return JSONObject.toJSON(map).toString();
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "/floorList", produces = "text/html;charset=UTF-8")
//    public String floorList(HttpServletRequest request) {
//        String build = request.getParameter("build");
//        System.out.println("+++build:" + build);
//        List<String> floors = repairMapper.selectAllFloor(build);
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("floors",floors);
//        return JSONObject.toJSON(map).toString();
//    }

    @ResponseBody
    @RequestMapping(value = "/roomList", produces = "text/html;charset=UTF-8")
    public String roomList(HttpServletRequest request) {
        String buildStr = request.getParameter("build");
        String floorStr = request.getParameter("floor");

        List<String> builds = repairMapper.selectAllBuild();
        if (buildStr == null || buildStr.equals("教学楼")) {
            buildStr = builds.get(0);
        }
        List<String> floors = repairMapper.selectAllFloor(buildStr);
        if (floorStr == null || floorStr.equals("楼层")) {
            floorStr = floors.get(0);
        }
        System.out.println("+++buildStr:" + buildStr + " floor:" + floorStr);
        Build build = new Build();
        build.setBuild(buildStr);
        build.setFloor(floorStr);
        List<String> rooms = repairMapper.selectAllRoom(build);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("builds",builds);
        map.put("floors",floors);
        map.put("rooms",rooms);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @PostMapping("/uploadimg")
    public String uploadimg(@RequestParam("openid") String openid, @RequestParam("file") MultipartFile file) {

        Map<String, Object> map = new HashMap<String, Object>();
        if (file.isEmpty()) {
            map.put("result",false);
            map.put("url","");
            return JSONObject.toJSON(map).toString();
        }
        System.out.println("++++upload openid:" + openid);
        String fileName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString();
        // 获取系统文件分隔符
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        String name = fileName.substring(0,fileName.lastIndexOf("."));
        String nowDate = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
        String timeStr = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
        try {
            File path=new File(ResourceUtils.getURL("classpath:").getPath());

            File uploadPath = new File(path.getAbsolutePath(),"/static/upfile/"  + nowDate + "/") ;
            //System.out.println("+++uploadPath:" + uploadPath.getPath());
            //文件夹路径不存在
            if (!uploadPath.exists() && !uploadPath.isDirectory()) {
                System.out.println("+++mrdir:" + uploadPath);
                uploadPath.mkdirs();
            }
            String nPath = uploadPath +"/"+ newName + "." + type;
            File newFile = new File(nPath);
            file.transferTo(newFile);

            String fileUrl = "upfile/" + nowDate + "/" + newName + "." + type;
            ImgFile imgFile = new ImgFile();
            imgFile.setOpenid(openid);
            imgFile.setOldName(name);
            imgFile.setUrlName(fileUrl);
            imgFile.setIsEnble(1L);
            imgFile.setTime(timeStr);
            if (repairMapper.insertImgFile(imgFile)==1){
                System.out.println("\r\n"+name + " upload success");
                map.put("result",true);
                map.put("url",fileUrl);
            }else{
                System.out.println(name + " upload fail");
                map.put("result",false);
                map.put("url","");
            }
        } catch (IOException e) {
            map.put("result",false);
            map.put("url","");
            System.out.println(e.toString());
        }
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/insertRepair", produces = "text/html;charset=UTF-8")
    public String insertRepair(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        Repair repair = new Repair();
        ObjectMapper mapper = new ObjectMapper();
        String timeStr = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
        String openid = request.getParameter("openid");
        String build = request.getParameter("build");
        String floor = request.getParameter("floor");
        String room = request.getParameter("room");
        String facility = request.getParameter("facility");
        String tid = request.getParameter("tid");
        String tname = request.getParameter("tname");
        String tfanlt = request.getParameter("tfanlt");
        String timg = request.getParameter("timg");
        repair.setOpenid(openid);
        repair.setBuild(build);
        repair.setFloor(floor);
        repair.setRoom(room);
        repair.setFacility(facility);
        repair.setTid(tid);
        repair.setTname(tname);
        repair.setTfanlt(tfanlt);
        repair.setTimg(timg);
        repair.setTtime(timeStr);
        int res = repairMapper.insertRepair(repair);
        if (res==1 && (!room.isEmpty()) && (!tname.isEmpty())){
            String str = "教学楼：" + build + "\r\n教室号：" + room + "\r\n故障设备：" + facility +
                    "\r\n故障描述：" + tfanlt + "\r\n报修老师：" + tname;
            String PostData = SMessage.STextMsg("yxb422576903", ParamesAPI.Oneself, ParamesAPI.Artisan,
                    ParamesAPI.AgentId, str);
            String access_token = WeixinUtil.getAccessTokenString(ParamesAPI.corpId, ParamesAPI.secret);
            int result = WeixinUtil.PostMessage(access_token, "POST", SMessage.POST_URL, PostData);

            System.out.println("+++insertRepair PostData:\r\n"+PostData + " \r\nresult:" + result);
        }
        try {
            map.put("res",res);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/updateRepair", produces = "text/html;charset=UTF-8")
    public String updateRepair(HttpServletRequest request){
        String content = null;
        Map map = new HashMap();
        Repair repair = new Repair();
        ObjectMapper mapper = new ObjectMapper();

        String wtime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
        String id = request.getParameter("id");
        String wid = request.getParameter("wid");
        String wname = request.getParameter("wname");
        String wimg = request.getParameter("wimg");
        String wfanlt = request.getParameter("wfanlt");
        repair.setId(Integer.valueOf(id));
        repair.setWid(wid);
        repair.setWname(wname);
        repair.setWimg(wimg);
        repair.setWtime(wtime);
        repair.setWfanlt(wfanlt);
        repair.setState(1);

        int res = repairMapper.updateRepair(repair);
        repair = repairMapper.selectRepairById(id);
        if (res==1){
            String msgStr = "老师您在" + repair.getBuild() + repair.getRoom() + "报修的" + repair.getFacility()
                    + "设备已检修,详细请进入小程序查看\r\n维修员：" + wname;
            String PostData = SMessage.STextMsg(repair.getTid(), ParamesAPI.Oneself, ParamesAPI.Oneself,
                    ParamesAPI.AgentId, msgStr);
            String access_token = WeixinUtil.getAccessTokenString(ParamesAPI.corpId, ParamesAPI.secret);
           int result =  WeixinUtil.PostMessage(access_token, "POST", SMessage.POST_URL, PostData);
           System.out.println("+++updateRepair PostData:\r\n"+PostData + " \r\nresult:" + result);
        }
        try {
            map.put("res",res);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    @ResponseBody
    @RequestMapping(value = "/selectRepair", produces = "text/html;charset=UTF-8")
    public String selectRepair(HttpServletRequest request) {
        String openid = request.getParameter("openid");
        String state = request.getParameter("state");
        Repair repair = new Repair();
        repair.setOpenid(openid);
        repair.setState(Integer.valueOf(state));
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("+++openid:" + openid + " state:" + state);
        List<Repair> list = repairMapper.selectRepair(repair);
        map.put("list",list);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/selectRepairById", produces = "text/html;charset=UTF-8")
    public String selectRepairById(HttpServletRequest request) {
        String id = request.getParameter("id");
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("+++id:" + id);
        Repair repair = repairMapper.selectRepairById(id);
        map.put("repair",repair);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/selectRepairByWidState", produces = "text/html;charset=UTF-8")
    public String selectRepairByWidState(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String wid = request.getParameter("wid");
        String state = request.getParameter("state");
        System.out.println("+++wid:" + wid + " state:" + state);
        List<Repair> list;

        if (state.equals("1")){
            Repair repair = new Repair();
            repair.setWid(wid);
            repair.setState(Integer.valueOf(state));
            list = repairMapper.selectRepairByWidState(repair);
        }else{
            list = repairMapper.selectRepairByState(state);
        }
        map.put("list",list);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/totalRepairState", produces = "text/html;charset=UTF-8")
    public String totalRepairState(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String openid = request.getParameter("openid");
        System.out.println("+++openid:" + openid);
        Status status= repairMapper.totalRepairState(openid);
        Teacher teacher = repairMapper.findUerByOpenId(openid);
        map.put("status",status);
        map.put("user",teacher);
        return JSONObject.toJSON(map).toString();
    }
}
